

import time
import ntptime
import machine



_latest_set_time=0

def update_time():
    global _latest_set_time
    t=time.gmtime()
    # a day = 86400 sec
    if not isUpdated(t) or time.time()-_latest_set_time > 86400 :
        print("Local time before synchronization：%s" %str(t))
        for i in range(5):
            try:
                #make sure to have internet connection
                ntptime.settime()
                print("Local time after synchronization：%s" %str(time.gmtime()))
                _latest_set_time=time.time()
                break
            except Exception as e:
                print("Error syncing time",e)
                time.sleep(3)
        return False
    else:
        return True
    


class timeMachine():
    def __init__(self,tz=8):
        self.timezone=tz
        self.offset=tz*60*60 # 28800
    def localtime(self):
        t=time.time()+self.offset
        return time.gmtime(t)
        # return time.localtime(t)

_timeMachine=None
# 设置时间：传入一个元组，格式为 (year, month, day, weekday, hours, minutes, seconds, subseconds)
# 注意：星期是从0到6 (0 是周一，6 是周日)
## 手动设置时间
def init(hour=0,minute=0,tz=8):
    # setDateTime
    rtc = machine.RTC()
    hour-=tz
    if hour<0:
        hour+=24
    hour=min(23,hour)
    # hour 要减掉时区, 因为 后面计算 localtime 加了时区
    rtc.datetime((2000, 1, 1, 5,  hour, minute, 0, 0))
    global _timeMachine
    if _timeMachine is None:
        _timeMachine=timeMachine(tz)

# def init(tz=8):
    
    
def localtime():
    return _timeMachine.localtime()


def gmtime():
    return time.gmtime()


def isUpdated(t):
    try:
        y=get_year(t)
    except:
        y=get_year(localtime())
    return y>2022
        

# tm_year=2018, tm_mon=10, tm_mday=2, 
#  tm_hour=12, tm_min=19, tm_sec=0, 
#   [6]0=周一:tm_wday=1, tm_yday=275, tm_isdst=0)

def get_year(t):
    return t[0]

def get_month(t):
    return t[1]

def get_day(t):
    return t[2]

def get_hour(t):
    return t[3]

def get_minute(t):
    return t[4]

def get_sec(t):
    return t[5]

def get_weekday(t):
    return t[6]

def get_yearday(t):
    return t[7]

